const mysql   = require('mysql2');
const ylog    = require('./log');
const { env } = process;

/**
 * 查询
 * @param {*} sql 
 * @param {*} db 
 */
function query(sql,db = {}){
    return new Promise((resolve,reject) => {
        try{
            const connection = mysql.createConnection(Object.assign({
                host: env.DBHOST,
                user: env.DBUSER,
                password: env.DBPASSWORD,
                database: env.DBDATABASE,
                port: env.DB_PORT
            },db));
            connection.query(sql,(err,results,fields) => {
                if(err){
                    ylog('sql查询错误:' + JSON.stringify(err),'_err','danger');
                    return reject(err);
                }
                connection.close();
                resolve(results);
            });
        }catch(e){
            ylog('数据库连接失败:'.JSON.stringify(e),'_err','danger');
        }
    });
}

module.exports = {
    query: query
};